#pragma once
#include<iostream>
#include<string>
#include"log.hpp"
#include<string.h>
#include"Init.hpp"

using namespace std;
extern Log lg;
Init init;
class Task
{
public:
    Task(int fd,const string&ip,uint16_t port)
    :sockfd_(fd),clientip_(ip),clientport_(port)
    {}
    Task()
    {}
    void run()
    {//这里加while循环就可以阻塞式通信，等到自己退出
        char buffer[4096];
        //读取客户端发送的信息
        ssize_t n=read(sockfd_,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n] = 0;
            cout << "client say#" << buffer << endl;
            string echo_string = "tcpserver echo#";//线程池版
            echo_string += buffer;
            //string echo_string = init.translation(buffer);//英汉词典版
            //向客户端处理后回显信息
            n = write(sockfd_, echo_string.c_str(), echo_string.size());
            if (n < 0)
            {
                lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            lg(Warning, "read error, sockfd: %d,client ip: %s,clientport: %d", sockfd_, clientip_.c_str(), clientport_);
        }
        close(sockfd_);
    }
    int GetSockfd()
    {
        return sockfd_;
    }
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }
private:
    int sockfd_;
    string clientip_;
    uint16_t clientport_;
};